package com.screen.screendisplay.controller;

import cn.hutool.core.date.DateUtil;
import com.screen.screendisplay.common.pojo.ApiResponse;
import com.screen.screendisplay.entity.electric.ElectricOpermonEquipFix;
import com.screen.screendisplay.entity.electric.ElectricProdoperCoalConsumeLr;
import com.screen.screendisplay.service.electric.*;
import com.screen.screendisplay.vo.electric.*;
import com.screen.screendisplay.vo.wholeproduct.IndustryProfileVO;
import com.screen.screendisplay.entity.electric.ElectricSafetyenvPollutant;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 火电 前端控制器
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Tag(name = "火电产业", description = "火电产业")
@RestController
@RequestMapping("/electric")
public class ElectricController {

    // 火电-生产经营-发电情况 service
    @Autowired
    private ElectricProdoperPowerGeneralService electricProdoperPowerGeneralService;
    @Autowired
    private ElectricProdoperHeatingService electricProdoperHeatingService;
    @Autowired
    private ElectricProdoperFuelService electricProdoperFuelService;
    @Autowired
    private ElectricProdoperFuelFromService electricProdoperFuelFromService;
    @Autowired
    private ElectricProdoperCoalConsumeLrService electricProdoperCoalConsumeLrService;
    @Autowired
    private ElectricProdoperCoalConsumeUrService electricProdoperCoalConsumeUrService;
    @Autowired
    private ElectricProdoperCoalConsumeService electricProdoperCoalConsumeService;
    @Autowired
    private ElectricOpermonEquipFixService electricOpermonEquipFixService;
    @Autowired
    private ElectricOverviewItemService electricOverviewItemService;
    @Autowired
    private ElectricOpermonEquipUseService electricOpermonEquipUseService;
    @Autowired
    private ElectricOpermonPlantService electricOpermonPlantService;
    @Autowired
    private ElectricSafetyenvPollutantService electricSafetyenvPollutantService;
    @Autowired
    private ElectricSafetyenvPlantRtService electricSafetyenvPlantRtService;


    /**
     * 发电计划完成情况
     * @return
     */
    @Operation(summary = "发电计划完成情况", description = "发电计划完成情况")
    @GetMapping("/prodoper/generation/plan-completion")
    public ApiResponse<FdPlanCompletionStatus> fdPlanCompletionStatus(@RequestParam(required = false) Integer year,
                                                                      @RequestParam(required = false) Integer month
            ) {
        if (year == null || month == null) {
            return ApiResponse.failed("参数错误");
        }
        FdPlanCompletionStatus status =
                electricProdoperPowerGeneralService.fdPlanCompletionStatus(year, month);
        return ApiResponse.succeed(status);
    }

    /**
     * 发电计划完成情况趋势图
     * @param year 年份
     * @return
     */
    @Operation(summary = "发电计划完成情况趋势图", description = "根据传入的年份查询当前年、去年所有的电厂每个月的完成情况统计趋势图")
    @GetMapping("/prodoper/generation/trend")
    public ApiResponse<List<FdComplateTrend>> complateTrend(@RequestParam(required = true) Integer year) {
        List<FdComplateTrend> trendList =
                electricProdoperPowerGeneralService.fdComplateTrend(year);
        return ApiResponse.succeed(trendList);
    }

    /**
     * 各个电厂供电完成情况
     * @param year
     * @return
     */
    @Operation(summary = "各个电厂供电完成情况", description = "各个电厂供电完成情况")
    @GetMapping("/electric/prodoper/generation/plant-completion")
    public ApiResponse<List<FdPowerPlantSupplyComplateStatus>> powerPlantSupplyComplateStatus(
            @RequestParam(required = false) Integer year) {
        List<FdPowerPlantSupplyComplateStatus> statusList =
                electricProdoperPowerGeneralService.fdPowerPlantSupplyComplateStatus(year);
        return ApiResponse.succeed(statusList);
    }

    /**
     * 供热计划完成情况
     * @return
     */
    @Operation(summary = "供热计划完成情况", description = "供热计划完成情况")
    @GetMapping("/prodoper/heating/plan-completion")
    public ApiResponse<GrPlanCompletionStatus> grPlanCompletionStatus(@RequestParam(required = false) Integer year,
                                                                      @RequestParam(required = false) Integer month) {
        if (year == null || month == null) {
            return ApiResponse.failed("参数错误");
        }
        GrPlanCompletionStatus status =
                electricProdoperHeatingService.grPlanCompletionStatus(year, month);
        return ApiResponse.succeed(status);
    }

    /**
     * 供热计划完成情况趋势图
     * @return
     */
    @Operation(summary = "供热计划完成情况趋势图", description = "根据传入的年份查询当前年、去年所有的电厂每个月的完成情况统计趋势图")
    @GetMapping("/prodoper/heating/trend")
    public ApiResponse<List<GrComplateTrend>> grComplateTrend(@RequestParam(required = true) Integer year) {
        if (year == null) {
            return ApiResponse.failed("参数错误");
        }
        List<GrComplateTrend> status =
                electricProdoperHeatingService.grComplateTrend(year);
        return ApiResponse.succeed(status);
    }


    /**
     * 各个电厂供热完成情况
     * @param year
     * @return
     */
    @Operation(summary = "各个电厂供热完成情况", description = "各个电厂供热完成情况")
    @GetMapping("/prodoper/heating/plant-completion")
    public ApiResponse<List<GrPowerPlantSupplyComplateStatus>> grPlanCompletionStatus(
            @RequestParam(required = false) Integer year) {
        List<GrPowerPlantSupplyComplateStatus> statusList =
                electricProdoperHeatingService.grPowerPlantSupplyComplateStatus(year);
        return ApiResponse.succeed(statusList);
    }

    /**
     * 燃料进耗存情况
     */
    @Operation(summary = "燃料进耗存情况", description = "燃料进耗存情况")
    @GetMapping("/prodoper/fuel/inventory")
    public ApiResponse<InventorySituation> inventorySituation(@RequestParam(required = false) Integer year) {
        if (year == null) {
            year = DateUtil.year(new Date());
        }
        InventorySituation situation =
                electricProdoperFuelService.inventorySituation(year);
        return ApiResponse.succeed(situation);
    }

    /**
     * 各电厂存煤以及可用天数情况
     * @param year
     * @return
     */
    @Operation(summary = "各电厂存煤以及可用天数", description = "各电厂存煤以及可用天数")
    @GetMapping("/prodoper/fuel/coal-availability")
    public ApiResponse<List<CoalStorageAndAvailableDays>> coalStorageAndAvailableDays(
                                                                @RequestParam(required = false) Integer year) {
        List<CoalStorageAndAvailableDays> list =
                electricProdoperFuelService.coalStorageAndAvailableDays(year);
        return ApiResponse.succeed(list);
    }

    /**
     * 煤炭来源分布情况
     * @param year
     * @return
     */
    @Operation(summary = "煤炭来源分布情况", description = "煤炭来源分布情况")
    @GetMapping("/prodoper/fuel/source-distribution")
    public ApiResponse<List<CoalSourceDistribution>> distributionCoalSources(
            @RequestParam(required = false) Integer year) {
        List<CoalSourceDistribution> list =
                electricProdoperFuelFromService.getCoalSourceDistributionByPlant(year);
        return ApiResponse.succeed(list);
    }

    /**
     * 火电生产实时负荷
     * @return
     */
    @Operation(summary = "火电生产实时负荷", description = "火电生产实时负荷")
    @GetMapping("/prodoper/coal-consumption/realtime-load")
    public ApiResponse<List<ElectricProdoperCoalConsumeLr>> prodoperCoalConsumelr() {
        List<ElectricProdoperCoalConsumeLr> list =
                electricProdoperCoalConsumeLrService.prodoperCoalConsume();
        return ApiResponse.succeed(list);
    }

    /**
     * 综合厂用电率概览
     * @param year 年份
     * @return PowerRateOverviewVO包含：yearAverage(全年平均厂用电率)、yoyChange(同比增加)、dataList(详细数据列表)
     */
    @Operation(summary = "生产经营-综合厂用电率", description = "获取电力产业综合厂用电率数据，包含全年平均用电率、同比变化和各月详细数据")
    @GetMapping("/prodoper/coal-consumption/power-rate")
    public ApiResponse<PowerRateOverviewVO> getPowerRateOverview(
            @RequestParam(required = false) Integer year) {
        
        // 创建综合厂用电率概览数据
        PowerRateOverviewVO overview = new PowerRateOverviewVO();
        
        // 使用当前年份或传入的年份，默认为2025年
        int currentYear = year != null ? year : 2025;
        
        // 设置全年平均厂用电率 - 5.8%
        overview.setYearAverage(new java.math.BigDecimal("5.8"));
        
        // 设置同比增加 - 提升0.3%
        overview.setYoyChange(new java.math.BigDecimal("0.3"));
        
        // 创建详细数据列表 - 同一个电厂6个月的数据
        List<PowerRateDataItemVO> dataList = new ArrayList<>();
        
        // 统一的电厂信息
        String powerPlantCode = "HM001"; // 霍林河电厂编码
        String powerPlantName = "霍林河电厂"; // 霍林河电厂名称
        
        // 生成1-6月的数据（同一个电厂的6条数据）
        for (int month = 1; month <= 6; month++) {
            PowerRateDataItemVO dataItem = new PowerRateDataItemVO();
            dataItem.setYear(currentYear);
            dataItem.setMonth(month);
            dataItem.setPowerPlantCode(powerPlantCode); // 电厂单位编码保持一致
            dataItem.setPowerPlantName(powerPlantName); // 电厂单位名称保持一致
            
            // 模拟当日用电率，基础值5.5%，随月份有小幅波动
            java.math.BigDecimal baseRate = new java.math.BigDecimal("5.5");
            java.math.BigDecimal monthVariation = new java.math.BigDecimal(month * 0.05); // 每月递增0.05%
            java.math.BigDecimal electricityRate = baseRate.add(monthVariation);
            dataItem.setElectricityRate(electricityRate);
            
            dataList.add(dataItem);
        }
        
        overview.setDataList(dataList);
        
        return ApiResponse.succeed(overview);
    }

    /**
     * 供电煤耗趋势
     * @return 只包含年份、月份、当月总耗煤量、去年同期总耗煤量的DTO列表（按月汇总）
     */
    @Operation(summary = "供电煤耗趋势", description = "供电煤耗趋势，返回年份、月份、当月总耗煤量、去年同期总耗煤量（按月汇总）")
    @GetMapping("/prodoper/coal-consumption/trend")
    public ApiResponse<List<CoalConsumeTrendDto>> prodoperCoalConsume() {
        // 首先获取原始数据
        List<CoalConsumeTrendDto> originalList =
                electricProdoperCoalConsumeService.prodoperCoalConsume();
        
        // 使用 Map 按年月进行分组汇总
        Map<String, CoalConsumeTrendDto> monthlyMap = new java.util.LinkedHashMap<>();
        
        for (CoalConsumeTrendDto item : originalList) {
            String key = item.getYear() + "-" + item.getMonth();
            
            if (monthlyMap.containsKey(key)) {
                // 如果该年月已存在，累加煤耗量
                CoalConsumeTrendDto existing = monthlyMap.get(key);
                existing.setCoalConsumption(
                    existing.getCoalConsumption().add(item.getCoalConsumption())
                );
                existing.setLastYearCoalConsumption(
                    existing.getLastYearCoalConsumption().add(item.getLastYearCoalConsumption())
                );
            } else {
                // 如果该年月不存在，创建新记录
                CoalConsumeTrendDto monthlyData = new CoalConsumeTrendDto();
                monthlyData.setYear(item.getYear());
                monthlyData.setMonth(item.getMonth());
                monthlyData.setCoalConsumption(item.getCoalConsumption());
                monthlyData.setLastYearCoalConsumption(item.getLastYearCoalConsumption());
                monthlyMap.put(key, monthlyData);
            }
        }
        
        // 转换为列表并按年月排序
        List<CoalConsumeTrendDto> result = new java.util.ArrayList<>(monthlyMap.values());
        result.sort((a, b) -> {
            int yearCompare = a.getYear().compareTo(b.getYear());
            if (yearCompare != 0) {
                return yearCompare;
            }
            return a.getMonth().compareTo(b.getMonth());
        });
        
        return ApiResponse.succeed(result);
    }


    /**
     * 火电产业总览统计
     * @param year 年份（必填）
     * @return 统计后的总览数据，包含各项指标的总和
     */
    @Operation(summary = "主要关键指标", description = "根据年份、月份、日期统计火电产业各项指标数据")
    @GetMapping("/overview/key-metrics")
    public ApiResponse<ElectricOverviewDto> getOverviewStatistics(
            @RequestParam(required = true) Integer year) {
        
        if (year == null) {
            return ApiResponse.failed("年份参数不能为空");
        }
        
        ElectricOverviewDto result = electricOverviewItemService.getOverviewStatistics(year);
        return ApiResponse.succeed(result);
    }

    /**
     * 设备状态检测
     * @param year 年份（必填）
     * @return 设备使用统计数据，包含机组总台数、装机总容量、运行台数等信息
     */
    @Operation(summary = "设备状态检测", description = "按年份统计设备使用情况，包含机组总台数量、装机总容量、机组运行台数、机组运行总容量、机组备用台数、机组备用总容量、机组检修台数、机组检修总容量")
    @GetMapping("/opermon/equipment-status")
    public ApiResponse<EquipmentUsageStatistics> getEquipmentUsageStatistics(
            @RequestParam(required = true) Integer year) {
        
        if (year == null) {
            year = DateUtil.year(new Date());
        }
        
        EquipmentUsageStatistics result = electricOpermonEquipUseService.getEquipmentUsageStatistics(year);
        return ApiResponse.succeed(result);
    }


    /**
     * 机组检修监测
     * @param year
     * @return
     */
    @Operation(summary = "机组检修监测", description = "机组检修监测")
    @GetMapping("/opermon/unit-maintenance")
    public ApiResponse<List<ElectricOpermonEquipFix>> opermonEquip(
            @RequestParam(required = false) Integer year) {
        List<ElectricOpermonEquipFix> list =
                electricOpermonEquipFixService.opermonEquip(year);
        return ApiResponse.succeed(list);
    }

    /**
     * 各电厂运行监测
     * @param year 年份（必填）
     * @return 各电厂容量统计数据，包含总容量、运行容量、停机容量、运行率
     */
    @Operation(summary = "各电厂运行监测", description = "按电厂维度统计每个电厂的总容量、运行容量、停机容量、运行率等指标")
    @GetMapping("/opermon/plant-operation")
    public ApiResponse<List<PlantCapacityStatistics>> getPlantCapacityStatistics(
            @RequestParam(required = true) Integer year) {
        
        if (year == null) {
            return ApiResponse.failed("年份参数不能为空");
        }
        
        List<PlantCapacityStatistics> result = electricOpermonPlantService.getPlantCapacityStatistics(year);
        return ApiResponse.succeed(result);
    }

    /**
     * 污染物排放情况
     * 按月份统计二氧化碳、二氧化硫排放量
     * @param year 年份（必填）
     * @return 月度排放量统计数据列表
     */
    @Operation(summary = "污染物排放情况", description = "按月份统计二氧化碳、二氧化硫每个月的排放量")
    @GetMapping("/safetyenv/pollutant-emission")
    public ApiResponse<List<MonthlyEmissionStatistics>> getMonthlyEmissionStatistics(
            @RequestParam(required = true) Integer year) {
        
        if (year == null) {
            return ApiResponse.failed("年份参数不能为空");
        }
        
        // 获取指定年份的月度排放数据
        List<ElectricSafetyenvPollutant> pollutantList = electricSafetyenvPollutantService.getByYear(year);
        
        // 转换为VO对象
        List<MonthlyEmissionStatistics> resultList = pollutantList.stream()
                .map(pollutant -> {
                    MonthlyEmissionStatistics statistics = new MonthlyEmissionStatistics();
                    statistics.setYear(pollutant.getYear());
                    statistics.setMonth(pollutant.getMonth());
                    statistics.setCo2Emission(pollutant.getCo2Emission());
                    statistics.setSo2Emission(pollutant.getSo2Emission());
                    statistics.setMonthName(pollutant.getMonth() + "月");
                    return statistics;
                })
                .collect(java.util.stream.Collectors.toList());
        
        return ApiResponse.succeed(resultList);
    }

    /**
     * 二氧化碳减排及节煤情况
     * @param year 年份（必填）
     * @return 月度减排效益统计数据列表
     */
    @Operation(summary = "二氧化碳减排及节煤情况", description = "按月份统计二氧化碳减排量、节煤量每个月的数据")
    @GetMapping("/safetyenv/co2-reduction")
    public ApiResponse<List<MonthlyReductionStatistics>> getMonthlyReductionStatistics(
            @RequestParam(required = true) Integer year) {
        
        if (year == null) {
            return ApiResponse.failed("年份参数不能为空");
        }
        
        // 获取指定年份的月度排放数据
        List<ElectricSafetyenvPollutant> pollutantList = electricSafetyenvPollutantService.getByYear(year);
        
        // 转换为VO对象
        List<MonthlyReductionStatistics> resultList = pollutantList.stream()
                .map(pollutant -> {
                    MonthlyReductionStatistics statistics = new MonthlyReductionStatistics();
                    statistics.setYear(pollutant.getYear());
                    statistics.setMonth(pollutant.getMonth());
                    statistics.setCo2Reduction(pollutant.getCo2Reduction());
                    statistics.setCoalSaving(pollutant.getCoalSaving());
                    statistics.setMonthName(pollutant.getMonth() + "月");
                    return statistics;
                })
                .collect(java.util.stream.Collectors.toList());
        
        return ApiResponse.succeed(resultList);
    }

    /**
     * 环保数据实时监测
     * @param year 年份（必填）
     * @return 电厂年度排放统计数据，包含公司、电厂、机组、状态、粉尘排放标准、硫化物排放标准、氮氧化物排放标准等信息
     */
    @Operation(summary = "环保数据实时监测", description = "根据传入年份按照电厂维度统计，统计每一个字段年累计，查询字段包括：公司、电厂、机组、状态、粉尘排放标准、硫化物排放标准、氮氧化物排放标准")
    @GetMapping("/safetyenv/realtime-monitoring")
    public ApiResponse<List<PlantAnnualEmissionStatistics>> getPlantAnnualEmissionStatistics(
            @RequestParam(required = true) Integer year) {
        
        if (year == null) {
            return ApiResponse.failed("年份参数不能为空");
        }
        
        List<PlantAnnualEmissionStatistics> result = electricSafetyenvPlantRtService.getPlantAnnualEmissionStatistics(year);
        return ApiResponse.succeed(result);
    }

    /**
     * 查询单位简介信息
     * @param industryType 产业分类（选填）
     * @param unitCode 单位编码（选填）
     * @return 单位简介信息，包含单位编码、单位名称、图片、简介
     */
    @Operation(summary = "电厂简介", description = "根据产业分类、单位编码查询单位简介信息，如果参数不传则返回默认数据")
    @GetMapping("/industry-profile")
    public ApiResponse<IndustryProfileVO> getIndustryProfile(
            @RequestParam(required = false) Integer industryType,
            @RequestParam(required = false) String unitCode) {
        
        // 创建一个默认的单位简介数据
        IndustryProfileVO profile = new IndustryProfileVO();
        profile.setUnitCode("HM001");
        profile.setUnitName("霍林河电厂");
        profile.setImgUrl("https://example.com/images/huolinhe-power-plant.jpg");
        profile.setDesc("霍林河电厂是内蒙古霍林河露天煤业股份有限公司下属的大型坑口电厂，始建于1990年，位于内蒙古自治区通辽市霍林郭勒市境内。" +
                "电厂总装机容量为2×600MW，年发电量约60亿千瓦时。电厂采用先进的超临界燃煤发电技术，具有高效、清洁、环保的特点。" +
                "作为国家西电东送北通道的重要电源点，霍林河电厂在保障电力供应、促进地区经济发展方面发挥着重要作用。");
        
        return ApiResponse.succeed(profile);
    }

    /**
     * 查询电厂运行监测信息
     * @param plantCode 单位编码（选填）
     * @return 电厂运行监测信息，包含运行容量、停机台数、停运容量、装机容量、运行机组台数、利用小时数
     */
    @Operation(summary = "电厂基本信息", description = "根据单位编码查询电厂运行监测信息，如果参数不传则返回默认数据")
    @GetMapping("/opermon/plant-monitor")
    public ApiResponse<PlantOperationMonitorVO> getPlantOperationMonitor(
            @RequestParam(required = false) String plantCode) {
        
        // 创建一个默认的电厂运行监测数据
        PlantOperationMonitorVO monitor = new PlantOperationMonitorVO();
        
        // 根据plantCode设置电厂名称
        String plantName = "霍林河电厂"; // 默认值
        if (plantCode != null) {
            switch (plantCode) {
                case "D_01_01":
                    plantName = "电力分公司";
                    break;
                case "D_01_02":
                    plantName = "通辽发电总厂";
                    break;
                case "D_01_03":
                    plantName = "霍林河坑口发电公司";
                    break;
                case "D_01_04":
                    plantName = "大板发电公司";
                    break;
                case "D_01_05":
                    plantName = "通辽热电公司";
                    break;
                case "D_01_06":
                    plantName = "盛发热电公司";
                    break;
                case "D_01_07":
                    plantName = "赤峰热电厂";
                    break;
                case "D_01_08":
                    plantName = "赤峰新城热电公司";
                    break;
                case "D_01_09":
                    plantName = "白音华自备电厂";
                    break;
                case "D_01_10":
                    plantName = "白音华坑口电厂";
                    break;
                case "D_01_11":
                    plantName = "通辽电投发电公司";
                    break;
                case "D_01_12":
                    plantName = "内蒙古通辽二发火电厂";
                    break;
                default:
                    plantName = "霍林河电厂";
                    break;
            }
        }
        
        monitor.setPlantCode(plantCode != null ? plantCode : "HM001");
        monitor.setPlantName(plantName);
        monitor.setOperatingCapacity(new java.math.BigDecimal("120.00")); // 运行容量 120万千瓦
        monitor.setOutageUnits(2); // 停机台数 2台
        monitor.setOutageCapacity(new java.math.BigDecimal("60.00")); // 停运容量 60万千瓦
        monitor.setInstalledCapacity(new java.math.BigDecimal("180.00")); // 装机容量 180万千瓦
        monitor.setRunningUnits(4); // 运行机组台数 4台
        monitor.setUtilizationHours(new java.math.BigDecimal("5280.50")); // 利用小时数 5280.5小时
        
        return ApiResponse.succeed(monitor);
    }

    /**
     * 查询生产情况信息
     * @param plantCode 单位编码（选填）
     * @return 生产情况信息，包含日发电量、日均煤耗、库存可用天数
     */
    @Operation(summary = "查询生产情况信息", description = "根据单位编码查询生产情况信息，如果参数不传则返回默认数据")
    @GetMapping("/prodoper/production-status")
    public ApiResponse<ProductionStatusVO> getProductionStatus(
            @RequestParam(required = false) String plantCode) {
        
        // 创建一个默认的生产情况数据
        ProductionStatusVO status = new ProductionStatusVO();
        status.setPowerPlantCode("HM001");
        status.setPowerPlantName("霍林河电厂");
        status.setDailyPowerGeneration(new java.math.BigDecimal("2800.50")); // 日发电量 2800.5万千瓦时
        status.setDailyCoalConsumption(new java.math.BigDecimal("3500.80")); // 日均煤耗 3500.8吨/天
        status.setStockAvailableDays(45); // 库存可用天数 45天
        
        return ApiResponse.succeed(status);
    }

    /**
     * 查询日供热量信息
     * @param plantCode 单位编码（选填）
     * @return 日供热量信息列表，返回一个月（31天）的数据
     */
    @Operation(summary = "查询日供热量信息", description = "根据单位编码查询日供热量信息，如果参数不传则返回默认数据（一个月31天的数据）")
    @GetMapping("/prodoper/daily-heating")
    public ApiResponse<List<DailyHeatingVO>> getDailyHeating(
            @RequestParam(required = false) String plantCode) {
        
        // 创建一个月（31天）的日供热量数据
        List<DailyHeatingVO> heatingList = new ArrayList<>();
        
        // 生成 2025年10月 的31天数据
        int year = 2025;
        int month = 10;
        
        for (int day = 1; day <= 31; day++) {
            DailyHeatingVO heating = new DailyHeatingVO();
            heating.setPowerPlantCode("HM001");
            heating.setPowerPlantName("霍林河电厂");
            heating.setYear(year);
            heating.setMonth(month);
            heating.setDay(day);
            
            // 模拟日供热量数据，基础值 8000 吉焦，随日期有小幅波动
            // 前10天：8000-8300吉焦
            // 中间10天：8300-8600吉焦
            // 后11天：8600-9000吉焦（供暖季开始，供热量增加）
            double baseHeating = 8000.0;
            if (day <= 10) {
                baseHeating += day * 30.0; // 8000 + (1-10)*30 = 8030-8300
            } else if (day <= 20) {
                baseHeating = 8300.0 + (day - 10) * 30.0; // 8330-8600
            } else {
                baseHeating = 8600.0 + (day - 20) * 36.0; // 8636-9000
            }
            
            heating.setDailyActualHeating(new java.math.BigDecimal(String.format("%.2f", baseHeating)));
            heatingList.add(heating);
        }
        
        return ApiResponse.succeed(heatingList);
    }

    /**
     * 查询运行水平信息
     * @param plantCode 单位编码（选填）
     * @return 运行水平信息列表，返回20条分钟级别的数据
     */
    @Operation(summary = "查询运行水平信息", description = "根据单位编码查询运行水平信息（实时负荷、负荷率），如果参数不传则返回默认数据（20条分钟级别数据）")
    @GetMapping("/prodoper/operation-level")
    public ApiResponse<List<OperationLevelVO>> getOperationLevel(
            @RequestParam(required = false) String plantCode) {
        
        // 创建20条分钟级别的运行水平数据
        List<OperationLevelVO> levelList = new ArrayList<>();
        
        // 获取当前时间，生成最近20分钟的数据
        java.time.LocalDateTime now = java.time.LocalDateTime.now();
        java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        
        // 装机容量设定为 120MW（用于计算负荷率）
        double installedCapacity = 120.0;
        
        for (int i = 19; i >= 0; i--) {
            OperationLevelVO level = new OperationLevelVO();
            level.setPowerPlantCode("HM001");
            level.setPowerPlantName("霍林河电厂");
            
            // 计算时间（从20分钟前到现在）
            java.time.LocalDateTime recordTime = now.minusMinutes(i);
            level.setRecordTime(recordTime.format(formatter));
            
            // 模拟实时负荷数据，基础负荷 95MW，随时间有小幅波动
            // 使用正弦函数模拟负荷波动
            double baseLoad = 95.0;
            double variation = 5.0 * Math.sin(i * Math.PI / 10.0); // 在90-100MW之间波动
            double currentLoad = baseLoad + variation;
            level.setCurrentLoad(new java.math.BigDecimal(String.format("%.2f", currentLoad)));
            
            // 计算负荷率 = (实时负荷 / 装机容量) * 100
            double loadRate = (currentLoad / installedCapacity) * 100.0;
            level.setLoadRate(new java.math.BigDecimal(String.format("%.2f", loadRate)));
            
            levelList.add(level);
        }
        
        return ApiResponse.succeed(levelList);
    }

    /**
     * 查询环保浓度监测信息
     * @param plantCode 单位编码（选填）
     * @return 环保浓度监测信息，包含二氧化硫、烟尘、氮氧化物的实时和历史浓度数据
     */
    @Operation(summary = "查询环保浓度监测信息", description = "根据单位编码查询环保浓度监测信息（二氧化硫、烟尘、氮氧化物的实时和历史数据），如果参数不传则返回默认数据")
    @GetMapping("/safetyenv/density-monitor")
    public ApiResponse<DensityMonitorVO> getDensityMonitor(
            @RequestParam(required = false) String plantCode) {
        
        // 创建一条环保浓度监测数据
        DensityMonitorVO monitor = new DensityMonitorVO();
        monitor.setPlantCode("HM001");
        monitor.setPlantName("霍林河电厂");
        
        // 获取当前时间
        java.time.LocalDateTime now = java.time.LocalDateTime.now();
        java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        monitor.setRecordTime(now.format(formatter));
        
        // 设置计量单位
        monitor.setUnit("mg/m³");
        
        // 二氧化硫浓度数据（标准值：35 mg/m³）
        monitor.setSo2AmountRealtime(28);  // 实时数据：28 mg/m³（符合标准）
        monitor.setSo2AmountHistory(30);   // 历史数据（上一小时）：30 mg/m³
        
        // 烟尘浓度数据（标准值：10 mg/m³）
        monitor.setDustAmountRealtime(7);  // 实时数据：7 mg/m³（符合标准）
        monitor.setDustAmountHistory(8);   // 历史数据（上一小时）：8 mg/m³
        
        // 氮氧化物浓度数据（标准值：50 mg/m³）
        monitor.setNitrogenAmountRealtime(42); // 实时数据：42 mg/m³（符合标准）
        monitor.setNitrogenAmountHistory(45);  // 历史数据（上一小时）：45 mg/m³
        
        return ApiResponse.succeed(monitor);
    }

    


}
